package com.chookss.tiku

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSON
import com.google.gson.Gson
import com.chookss.tiku.entity.ExamResult
import com.chookss.tiku.entity.LiveResult
import com.chookss.tiku.entity.Subject
import com.chookss.tiku.response.GetExamCountDownResponse
import com.chookss.tiku.response.SimulateSubjectList
import com.chookss.tiku.response.SimulateSubmit
import com.chookss.tools.XJson
import com.chookss.tools.httpForm
import com.chookss.tools.old.SignUtils
import com.johnrambo.ktea.common.logger
import com.johnrambo.ktea.common.parseObject
import com.johnrambo.ktea.ktExtends.ShareUtils
import com.johnrambo.ktea.net.http.Method
import com.johnrambo.ktea.net.http.http

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/23 16:15
 * Note: 模拟试卷数据类
 */
open class AnswerExamViewModel : SubjectAnswerViewModel() {
    //1001 选择题
    //1002 多选题
    //1003 判断题

    //题目列表
    val subjectList = mutableListOf<Subject>()
    var mContext: Context? = null

    //我选择的各题目答案 key为subjectCode, value:答案列表lv
    var myAnswerMap = HashMap<Int, SimulateSubmit.Answer>()
    var examCode: String? = null
    var recordType: String? = null

    fun putMyAnswer(context:Context,index: Int, list: List<String>) {
        if (list.isEmpty()) {
            myAnswerMap.remove(index)
        } else {
            var subject = subjectList[index]
            myAnswerMap[index] = SimulateSubmit.Answer().apply {
                subjectCode = subject.subjectCode
                if(subject.subjectTypeCode.equals("1004")){
                    optionLvlNo = list.joinToString("@#^")
                }else if(subject.subjectTypeCode.equals("1005")){
                    if(list.size>0){
                        optionLvlNo = list.get(0)
                    }
                }else{
                    optionLvlNo = list.joinToString(",")
                }

                score = getSubjectScore(subject, list)
                subjectTypeCode = subject.subjectTypeCode
            }
        }
        var data= Gson().toJson(myAnswerMap)
        ShareUtils().putString(context, examCode + "_answer", data)
    }

    private fun createSubjectResult(
        subjectList: List<Subject>,
        listIndex: Int
    ): LiveResult<Subject> {
        if (subjectList.size > listIndex) {
            return LiveResult(subjectList[listIndex])
        } else {//没有结果,结束了
            return LiveResult(null)
        }
    }

    //下载题目列表
    override fun getSubject(index: Int): LiveData<LiveResult<Subject>> {
        var liveResult = MutableLiveData<LiveResult<Subject>>()
        if (subjectList.size > 0) {
            liveResult.postValue(createSubjectResult(subjectList, index))
            return liveResult
        }
        //考试
        subjectList.clear()
        subjectList.addAll(XJson.getDataList(mContext, examCode, Subject::class.java))
        if (subjectList.size == 0) {
            jobs + httpForm<SimulateSubjectList.Response> {
                url = "api/exam/paper/getPaperSubject"
                params = mutableMapOf("examCode" to examCode)
                onSuccess = {
                    liveResult.postValue(createSubjectResult(subjectList, index))
                }
                onError = {
                    this@AnswerExamViewModel.examCode = null
                    liveResult.postValue(LiveResult(Error(it)))
                }
            }
        } else {
            liveResult.postValue(createSubjectResult(subjectList, index))
        }


        return liveResult
    }

    //是否已回答所有题目
    fun hasAnswerAll() = subjectList.size <= myAnswerMap.size

    //提交所有答案到服务器
    fun submitAllAnswers(time: Long, answerType: String): LiveData<LiveResult<ExamResult>> {
        var liveResult = MutableLiveData<LiveResult<ExamResult>>()

        var request = SimulateSubmit.Request()
        request.answerType = answerType
        request.timeLength = (time / 1000).toString()
        request.examCode = examCode
        request.answerList = subjectList.mapIndexed { index, subject ->
            myAnswerMap[index] ?: SimulateSubmit.Answer().apply {
                subjectCode = subject.subjectCode
                score = subject.subjectScore
                subjectTypeCode = subject.subjectTypeCode
            }
        }

        var timestamp = SignUtils.getTimeStamp() //20201208125238
        var nonce = SignUtils.getRandomString(14)
        var sign = SignUtils.makeSignStr(mutableMapOf(), timestamp, nonce, false)
        logger("sign:${sign}")
        var jsonText = JSON.toJSONString(request)

        jobs + http {
            url = "api/exam/paper/submitPaper?timestamp=${timestamp}&nonce=${nonce}&sign=${sign}"
            method = Method.POSTJSON
            params = mutableMapOf("body" to jsonText)
            onSuccess = {
                var result: SimulateSubmit.Response? = it.parseObject<SimulateSubmit.Response>()
                if (result?.code != 200) {
                    liveResult.postValue(LiveResult(Error(result?.msg)))
                } else {
                    liveResult.postValue(LiveResult(result.data))
                }
            }
            onError = {
                liveResult.postValue(LiveResult(Error("服务器异常，请稍后重试")))
            }
        }

        return liveResult
    }

    private fun findSubject(subjectCode: String): Subject? {
        for (subject in subjectList) {
            if (subject.subjectCode == subjectCode) {
                return subject
            }
        }
        return null
    }

    //获取题目的得分
//    s_chaobo:
//    模拟卷是后端判断做对做错啊，应该所有的题目都有分值这个字段
//
//    Liu:
//    之前我以为是前段判断对错
//
//    s_chaobo:
//    我看 考试的结果记录 是做对了两道题 但是只有一道题 传了分值
//
//    Liu:
//    那测试题 提交也是全部带分值的吧
//
//    s_chaobo:
//    练习的不用 练习的是你们判断正误
//
//    Liu:
//    ok
    private fun getSubjectScore(subject: Subject, myAnswers: List<String>): String {
//        var answers = subjectAnswerCache[subject.subjectCode]
//        if (answers == null || myAnswers.isEmpty()) {
//            return "0"
//        }
//        var tmp = ArrayList(myAnswers)
//        var rightCount = 0
//        answers.filter { it.isRightAnswer == "1" }.forEach {
//            tmp.remove(it.lvlNo)
//            rightCount++
//        }
//        if (myAnswers.size != rightCount || tmp.isNotEmpty()) {
//            return "0"
//        }
        return subject.subjectScore ?: "0"
    }

    //    examCode	true	String	考试编码
//    examTimeLength	true	String	考试时长，从考试信息中可获取该字段
    open fun getExamCountDown(examTimeLength: String): LiveData<LiveResult<Long>> {
        var liveResult = MutableLiveData<LiveResult<Long>>()
        jobs + httpForm<GetExamCountDownResponse> {
            url = "api/exam/getExamCountDown"
            if (examTimeLength.equals("")) {
                params = mutableMapOf("examCode" to examCode, "examTimeLength" to "0")
            } else {
                params = mutableMapOf("examCode" to examCode, "examTimeLength" to examTimeLength)
            }

            onSuccess = {
                liveResult.postValue(LiveResult(it.data.countDown))
            }
            onError = {
                liveResult.postValue(LiveResult(Error(it)))
            }
        }
        return liveResult
    }

}